//
//  SelectCityViewController.m
//  CarLife
//
//  Created by yu on 2017/10/30.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "SelectCityViewController.h"
#import "PinYinForObjc.h"
#import "CityModel.h"

@interface SelectCityViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (weak, nonatomic  ) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITableView *resultTableView;

@property (nonatomic, strong) NSMutableArray *cityList;

@property (nonatomic, strong) NSArray *resultCityList;

@property (nonatomic, strong) NSMutableArray *titleList;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (weak, nonatomic  ) IBOutlet UIView *shadeView;

@end

static NSString *kCityCellIdentifier = @"CityCellIdentifier";

@implementation SelectCityViewController

- (IBAction)shadeViewTap:(id)sender {
    [self.shadeView setHidden:YES];
    [self.textField resignFirstResponder];
    
    self.cancelBtn.sd_layout.widthIs(0);
    [self.cancelBtn updateLayout];
    
    self.textField.sd_layout.rightSpaceToView(self.view, 13);
    [self.textField updateLayout];
}

- (IBAction)cancelAction:(id)sender {
    [self.shadeView setHidden:YES];
    [self.textField resignFirstResponder];
    [self.resultTableView setHidden:YES];
    self.textField.text = @"";
    
    self.cancelBtn.sd_layout.widthIs(0);
    [self.cancelBtn updateLayout];
    
    self.textField.sd_layout.rightSpaceToView(self.view, 13);
    [self.textField updateLayout];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self.shadeView setHidden:NO];
    
    self.cancelBtn.sd_layout.widthIs(55);
    [self.cancelBtn updateLayout];
    
    self.textField.sd_layout.rightSpaceToView(self.view, 65);
    [self.textField updateLayout];
}

- (void)setTextField:(UITextField *)textField {
    _textField = textField;
    
    UIView *leftview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 7, 0)];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
}

- (IBAction)textFieldEditingChanged:(UITextField *)textField {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cityName CONTAINS[cd] $KEY"];
    NSPredicate *keyPredicate = [predicate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:textField.text forKey:@"KEY"]];
    
    self.resultCityList = [self.dataArray filteredArrayUsingPredicate:keyPredicate];
    if (self.resultCityList.count > 0) {
        [self.resultTableView setHidden:NO];
    }else {
        [self.resultTableView setHidden:YES];
    }
    [self.resultTableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择城市";
    [self setLeftImageNamed:@"back_gray" action:@selector(returnAction)];
    [self loadCityData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setDefaultNavigationBar];
}

- (void)loadCityData {
    [self.requestTool loadAllCitySuccess:^(NSMutableArray *dataArray) {
        self.dataArray = [NSMutableArray arrayWithArray:dataArray];
        // 汉字转拼音首字母
        [self chineseToPinYin];
        [self.tableView reloadData];
    } failure:^(NSString *error) {
    }];
}

#pragma mark - 汉字转拼音
- (void)chineseToPinYin{
    // 大数组套小数组
    self.cityList = [[NSMutableArray alloc] init];
    for (int i = 'a'; i <= 'z'; i++) {
        // 建立小数组
        NSMutableArray *array = [NSMutableArray array];
        // 添加到大数组中
        [self.cityList addObject:array];
    }
    // 找到每个城市的名称
    for (int i = 0; i < self.dataArray.count; i++) {
        CityModel *model = self.dataArray[i];
        // 转换
        NSString *headerName = [PinYinForObjc chineseConvertToPinYin:model.cityName];
        
        // 取第一个字符
        char firstChar = [headerName characterAtIndex:0];
        // PPLog(@"%c",firstChar - 'a');
        // 将对应的城市放到小数组中
        // 1.寻找存储该城市的小数组
        // 2.将该城市存入小数组中
        [self.cityList[firstChar - 'a'] addObject:model];
        // PPLog(@"%@",self.cityList);
    }
    // 去除空数组
    [self.cityList removeObject:@[]];
    
    //初始化数组
    self.titleList = [[NSMutableArray alloc] init];
    //得到段头文字
    for (int i = 0; i < self.cityList.count; i++) {
        // 依次找到每个小数组,并取得数组第一个元素
        CityModel *model = self.cityList[i][0];
        // 得到首字母
        NSString *cityName = [PinYinForObjc chineseConvertToPinYinHead:model.cityName];
        // 取第一个字符
        char c = [cityName characterAtIndex:0];
        
        NSString *firstChar = NSStringFormat(@"%c",c);
        NSString *firstCharUpper = [firstChar uppercaseString];
        // 存储到数组中
        [self.titleList addObject:firstCharUpper];
    }
}

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        return self.cityList.count;
    } else {
        return 1;
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return [self.cityList[section] count];
    } else {
        return [self.resultCityList count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCityCellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCityCellIdentifier];
    }
    CityModel *model;
    if (tableView == self.tableView) {
        model = self.cityList[indexPath.section][indexPath.row];
    } else {
        model = self.resultCityList[indexPath.row];
    }
    if (@available(iOS 13.0, *)) {
        cell.contentView.backgroundColor = UIColor.secondarySystemGroupedBackgroundColor;
        cell.textLabel.textColor = UIColor.labelColor;
    } else {
        cell.contentView.backgroundColor = UIColor.whiteColor;
        cell.textLabel.textColor = kTextBlackColor;
    }
    cell.textLabel.text = model.cityName;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CityModel *model;
    if (tableView == self.tableView) {
        model = self.cityList[indexPath.section][indexPath.row];
    } else {
        model = self.resultCityList[indexPath.row];
    }
//    PPLog(@"city name = %@",model.cityName);
//
//    PPLog(@"engine == %@",model.engine);
//    PPLog(@"engineno == %@",model.engineno);
//
//    PPLog(@"class1 == %@",model.class1);
//    PPLog(@"classno == %@",model.classno);
    if ([self.delegate respondsToSelector:@selector(chooseCityModel:)]) {
        [self.delegate chooseCityModel:model];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    if (@available(iOS 13.0, *)) {
        header.textLabel.textColor = UIColor.labelColor;
    } else {
        header.textLabel.textColor = kTextBlackColor;
    }
    header.contentView.backgroundColor = self.tableView.backgroundColor;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return 28;
    } else {
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

//头视图的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return self.titleList[section];
    } else {
        return nil;
    }
}

//索引
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return self.titleList;
    } else {
        return nil;
    }
}

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSArray *)resultCityList {
    if (_resultCityList == nil) {
        _resultCityList = [NSArray array];
    }
    return _resultCityList;
}

- (void)returnAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
